import sys
import re

databaseDir = sys.argv[1]
sampleName = sys.argv[2]
workdir = sys.argv[3]
TCRChainsTable = sys.argv[4]  #eg:P44.TCRExt.xls(TCR,TCRIndex,ChoBar,chain,rawseq,VGene,DGene,JGene,CDR3Acid1,type,ExtSeq,Acid,LinkAcid,CDR3Acid2,CDR3Dna1)

# databaseDir = "/home/hsmy/code/ik/TCR/singlecell/TCRPriDesign/DB"
# sampleName = "p"
# workdir = "/home/hsmy/mob"
# TCRChainsTable = "/home/hsmy/mob/p.TCRExtSeq.xls"

#finish in 2020.7.17
#output: TCRPriDesign.Detail.xls,TCRPriDesign.Final.xls

#pri adjust
def translate(seq):
    def StriOrderlyByNum(stri, num):
        if len(stri) % num == 0:
            return stri
        else:
            redundantNum = len(stri) % num
            totalNum = len(stri)
            return stri[0:totalNum - redundantNum]

    table = {
        'ATA': 'I', 'ATC': 'I', 'ATT': 'I', 'ATG': 'M',
        'ACA': 'T', 'ACC': 'T', 'ACG': 'T', 'ACT': 'T',
        'AAC': 'N', 'AAT': 'N', 'AAA': 'K', 'AAG': 'K',
        'AGC': 'S', 'AGT': 'S', 'AGA': 'R', 'AGG': 'R',
        'CTA': 'L', 'CTC': 'L', 'CTG': 'L', 'CTT': 'L',
        'CCA': 'P', 'CCC': 'P', 'CCG': 'P', 'CCT': 'P',
        'CAC': 'H', 'CAT': 'H', 'CAA': 'Q', 'CAG': 'Q',
        'CGA': 'R', 'CGC': 'R', 'CGG': 'R', 'CGT': 'R',
        'GTA': 'V', 'GTC': 'V', 'GTG': 'V', 'GTT': 'V',
        'GCA': 'A', 'GCC': 'A', 'GCG': 'A', 'GCT': 'A',
        'GAC': 'D', 'GAT': 'D', 'GAA': 'E', 'GAG': 'E',
        'GGA': 'G', 'GGC': 'G', 'GGG': 'G', 'GGT': 'G',
        'TCA': 'S', 'TCC': 'S', 'TCG': 'S', 'TCT': 'S',
        'TTC': 'F', 'TTT': 'F', 'TTA': 'L', 'TTG': 'L',
        'TAC': 'Y', 'TAT': 'Y', 'TAA': '_', 'TAG': '_',
        'TGC': 'C', 'TGT': 'C', 'TGA': '_', 'TGG': 'W',
    }

    seq1 = StriOrderlyByNum(seq, 3)
    protein = ""

    if len(seq1) % 3 == 0:
        for i in range(0, len(seq1), 3):
            codon = seq1[i:i + 3]
            protein += table[codon]
    else:
        print("please check seq num!", len(seq1) % 3)

    return protein


def readToDict(aFile):
    subDict = {}
    f=open(aFile)
    line=f.readline()
    while line:
        temp = line.strip("\n").split("\t")
        raw = temp[0]
        new = temp[1]

        if raw not in subDict:
            subDict[raw] = []

        if new not in subDict[raw]:
            subDict[raw].append(new)

        line=f.readline()
    f.close()
    return subDict


def readDB(dbdir):
#need function: readToDict

    LowFracFile = "%s/LowFrac.txt" % (dbdir)
    ContBaseFile = "%s/ContBase.txt" % (dbdir)
    ContGCFile = "%s/ContGC.txt" % (dbdir)

    LowFracDict = readToDict(LowFracFile)
    ContBaseDict = readToDict(ContBaseFile)
    ContGCDict = readToDict(ContGCFile)

    result = [LowFracDict,ContBaseDict,ContGCDict]
    return result

def LowFracSub(RawSeq):
    #step1: Low Frac Sub
    seq = RawSeq
    finalseq = ""
    for i in range(0,len(seq)-2,3):
        subseq = seq[i:i+3]
        if subseq in LowFracDict:
            finalseq += LowFracDict[subseq][0]
        else:
            finalseq += subseq
    return finalseq

def Large5Cont(RawSeq):
    #step2: >5 continuation base
    seq = RawSeq
    SeqLen = len(seq)

    for i in range(0,SeqLen-5):
        ThisBase = seq[i]
        ContNum = 1

        for y in range(i+1,SeqLen):#calcate repeat base same as this base num. if not the same, then i go on next
            AftBase = seq[y]

            if AftBase == ThisBase:
                ContNum += 1
            else:
                break

        if ContNum > 5:
            AcidNum = i / 3   #start from 0
            AcidPos = i % 3   #0,1,2

            NextAcidSeq = seq[(AcidNum+1)*3:(AcidNum+2)*3]
            if NextAcidSeq in ContBaseDict:
                NextAcidSubSeq = ContBaseDict[NextAcidSeq][0]
                seq = "%s%s%s" % (seq[0:(AcidNum+1)*3],NextAcidSubSeq,seq[(AcidNum+2)*3::])
            else:
                print "sub acid error!!!",NextAcidSeq
                seq = "-"
                return seq

    return seq

def Large7ContGC(RawSeq):
    #step3: >7 continuation GC
    seq = RawSeq
    SeqLen = len(seq)

    for i in range(0,SeqLen-7):
        ThisBase = seq[i]
        if ThisBase != "C" and ThisBase != "G":
            continue

        ContNum = 1

        for y in range(i+1,SeqLen):#calcate repeat base same as this base num. if not the same, then i go on next
            AftBase = seq[y]

            if AftBase == "C" or AftBase == "G":
                ContNum += 1
            else:
                break

        if ContNum > 7:
            AcidNum = i / 3   #start from 0
            AcidPos = i % 3   #0,1,2

            NextAcidSeq = seq[(AcidNum+1)*3:(AcidNum+2)*3]
            if NextAcidSeq in ContGCDict:
                NextAcidSubSeq = ContGCDict[NextAcidSeq][0]
                seq = "%s%s%s" % (seq[0:(AcidNum+1)*3],NextAcidSubSeq,seq[(AcidNum+2)*3::])
            else:
                print "sub acid error!!!",NextAcidSeq
                seq = "-"
                return seq

    return seq

def PriSeqSub(RawSeq):
#need sub database dict:LowFracDict,ContBaseDict,ContGCDict


    tempSeq = LowFracSub(RawSeq)
    tempSeq = Large5Cont(tempSeq)
    finalSeq = Large7ContGC(tempSeq)

    if translate(finalSeq) == translate(RawSeq):
        return finalSeq
    else:
        return "-"

#pri adjust end.

readDBResult = readDB(databaseDir)
LowFracDict = readDBResult[0]
ContBaseDict = readDBResult[1]
ContGCDict = readDBResult[2]

#base function
def DealVGene(VGeneRaw):
#TRAV38-2DV8 -> TRAV38-2,TRAV14DV8 -> TRAV14
    n = re.match("(.*)(DV)(.*)",VGeneRaw) #TRAV14DV8
    if n:
        VGeneNew = n.group(1)
    else:
        VGeneNew = VGeneRaw
    return VGeneNew.replace("/","")

#database
def checkFileExist(filePath):
    import os
    if os.path.exists(filePath):
        print "[yes]",filePath
        return True
    else:
        print "[no]",filePath
        return False

def getJPriAADict(Table):
#output:{AJ:{}}
    JPriAADict={}
    f=open(Table)
    line=f.readline()#head:AJ,PrimerName,AA
    line=f.readline()
    while line:
        temp=line.strip("\n").split("\t")
        J = temp[0]
        Pri = temp[1]
        AA = temp[2]
        if J not in JPriAADict:
            JPriAADict[J]={}
            JPriAADict[J][Pri] = AA
        else:
            if Pri not in JPriAADict[J]:
                JPriAADict[J][Pri] = AA
            else:
                print "error!repeat:",Pri
        line=f.readline()
    f.close()

    return JPriAADict

def fromTableGetMap(table,keyCol,valueCol):

    #read head
    colDict={}
    f=open(table)
    line=f.readline()
    line=line.strip("\n").split("\t")
    c=0
    for i in line:
        if i not in colDict:
            colDict[i]=c
            c+=1
        else:
            print "warning:col name is repeat!",i
            f.close()
            return False
    f.close()

    #check
    if keyCol not in colDict:
        print "error:",keyCol
        return False
    if valueCol not in colDict:
        print "error:",colDict
        return False

    #get map
    mapDict={}
    f=open(table)
    line=f.readline()
    line=f.readline()
    while line:
        temp=line.strip("\n").split("\t")
        key=temp[colDict[keyCol]]
        mapVal=temp[colDict[valueCol]]
        if key not in mapDict:
            mapDict[key] = mapVal
        else:
            print "key has repeat!",key
            return False
        line=f.readline()
    f.close()
    return mapDict

def getDatabase(databaseDir):

    #get database file path
    JPriFile = "%s/AJPri.2.txt" % (databaseDir)
    VGeneTable = "%s/VGeneSeq.txt" % (databaseDir)
    OLTable = "%s/2R1FPriOLSeq.txt" % (databaseDir)
    VGeneLongTable = "%s/VGeneLongSeq.txt" % (databaseDir)
    R2F1DNASeqTable = "%s/2R1FPriDNASeq.txt" % (databaseDir)

    print "check database files:"
    flag = True
    flag = checkFileExist(JPriFile)
    flag = checkFileExist(VGeneTable)
    flag = checkFileExist(OLTable)
    flag = checkFileExist(VGeneLongTable)
    flag = checkFileExist(R2F1DNASeqTable)

    if flag:
        print "check finish!"
    else:
        return False

    #get database
    JPriAADict = getJPriAADict(JPriFile)
    VGeneSeqDict = fromTableGetMap(VGeneTable,"VGene","Seq")
    PriOLSeqDict = fromTableGetMap(OLTable,"PriName","OLSeq")
    VGeneLongSeqDict = fromTableGetMap(VGeneLongTable,"VGene","Seq")
    R2F1PriDNASeqDict = fromTableGetMap(R2F1DNASeqTable,"PrimerName","DNASeq")

    result = [JPriAADict,VGeneSeqDict,PriOLSeqDict,VGeneLongSeqDict,R2F1PriDNASeqDict]
    return result

#database end.

def getTCRinput(TCRTable):  #read TCR table
#need col:TCRName,Type,VGene,DGene,JGene,CDR3Acid2,CDR3Dna1

    TCRInfoDict={}
    f = open(TCRTable)
    f.readline()
    line = f.readline()
    while line:
       temp = line.strip("\n").split("\t")
       TCR = temp[0]

       #table format
       #NeedInfo = [temp[0],temp[7],temp[8],temp[9],temp[10],temp[11],temp[12]]
       NeedInfo = [temp[0],temp[9],temp[5],temp[6],temp[7],temp[13],temp[14]]

       if TCR not in TCRInfoDict:
           TCRInfoDict[TCR] = []
           TCRInfoDict[TCR].append(NeedInfo)
       else:
           TCRInfoDict[TCR].append(NeedInfo)
       line=f.readline()
    f.close()

    return TCRInfoDict

def TCRNameSort(TCRList):
    UnRe = []
    NumTCRDict={}
    NumList=[]
    TCRSortList=[]

    for i in TCRList:
        m=re.match("(TCR-)([0-9]*)",i)
        if m:
            Num = int(m.group(2))
            if Num not in NumTCRDict:
                NumTCRDict[Num] = i
                NumList.append(Num)
            else:
                print "repeat:",i
        else:
            UnRe.append(i)
            print "can't shibie:",i

    NumList.sort()
    for i in NumList:
        TCRSortList.append(NumTCRDict[i])

    return TCRSortList

def getJGene(ABType,JGene):
    if ABType == "A":
        m = re.match("(TRAJ)([0-9]+)",JGene)
        if m:
            JGene2 = "AJ%s" % (m.group(2))
            return JGene2
        else:
            return False
    elif ABType == "B":
        m = re.match("(TRBJ)(\S+)",JGene)
        if m:
            JGene2 = "BJ%s" % (m.group(2))
            return JGene2
        else:
            return False
    else:
        return False


def CDR3SeqDeal(ABType,CDR3Acid,CDR3Dna,JGenePriAASeq):

    def MatSeq1(seq,DBDict):
        Cho = "-"
        MaxLen = 0
        MatPos = False
        for i in DBDict:
            if seq.find(DBDict[i]) > -1:
                if len(DBDict[i]) > MaxLen:
                    MaxLen = len(DBDict[i])
                    Cho = i
                    MatPos = seq.find(DBDict[i])

        if MatPos:
            result = [MatPos,Cho]
            return result
        else:
            return False

    #CDR3SeqDeal main
    if ABType == "A":
        CDR3Acid = "%sPD" % (CDR3Acid)

    elif ABType == "B":
        CDR3Acid = "%sKNVFPP" % (CDR3Acid)

    else:
        return False

    MatchResult = MatSeq1(CDR3Acid,JGenePriAASeq)
    
    if MatchResult:
        MatPos = MatchResult[0] 
        ChoPri = MatchResult[1]

        CDR3AcidBefNoMat = CDR3Acid[1:MatPos]
        FCDR3Dna = CDR3Dna[3:3+len(CDR3AcidBefNoMat)*3]
        #print "MatPos:",MatPos,"ChoPri:",ChoPri,"CDR3AcidBefNoMat:",CDR3AcidBefNoMat,"FCDR3Dna:",FCDR3Dna
        result = [ChoPri,FCDR3Dna]
        return result
    else:
        return False

def seqFXHB2(seqstr):
    result = seqstr[::-1]
    stri=""
    for i in result:
        if i == "A":
            stri+="T"
        elif i == "T":
            stri+="A"
        elif i == "C":
            stri+="G"
        elif i == "G":
            stri+="C"
        else:
            stri+="N"
    return stri


def get1R2FPri(ABType,CDR3Seq,OLSeq,VGeneSeq):
#get primary 1R(chain A) 2F(chain B)
#1R,like 2R-13-1 OL & A1-CDR3 DNA Seq-Complementary Reverse & AV1-2
#2F,like TRBV11-2 & B1-CDR3 DNA seq & 1F-21-1 OL


    if ABType == "A":
        CDR3SeqR = seqFXHB2(CDR3Seq)
        PriSeq = "%s%s%s" % (OLSeq,CDR3SeqR,VGeneSeq)
        return PriSeq

    elif ABType == "B":
        PriSeq = "%s%s%s" % (VGeneSeq,CDR3Seq,OLSeq)
        return PriSeq

    else:
        return False

def getTCRSeq(ABType,F1R2Pri,CDR3Dna,VGeneLong):
    GDB = "TCCCGAGGTGGCCGTGTTCGAGCCAAGCGAGGCAGAGATCAGCCACACCCAGAAGGCCACACTGGTGTGCCTGGCCACCGGCTTCTACCCCGACCACGTGGAGCTGAGCTGGTGGGTGAACGGCAAGGAGGTGCACAGCGGCGTGAGCACCGACCCTCAGCCCCTGAAGGAGCAGCCCGCCCTGAACGACAGCAGATACTGCCTGAGCAGCAGGCTGCGCGTGAGCGCCACCTTCTGGCAGAACCCTCGCAACCACTTCCGCTGCCAGGTGCAGTTCTACGGCCTGAGCGAGAACGACGAGTGGACCCAGGACAGAGCCAAGCCCGTGACCCAGATCGTGAGCGCCGAGGCCTGGGGAAGAGCCGACTGCGGCTTCACCAGCGAGAGCTACCAGCAGGGCGTGCTGAGCGCCACCATCCTGTACGAAATCCTGCTGGGCAAAGCCACCCTGTACGCCGTGCTGGTGAGCGCCCTGGTGCTGATGGCCATGGTGAAGAGAAAGGACAGCAGAGGCAGCGGAGCCACCAACTTCAGCCTGCTGAAGCAGGCTGGCGACGTGGAGGAGAACCCTGGGCCC"
    GDA = "CCTGCCGTGTACCAGCTGAGAGACTCTAAATCCAGCGACAAGTCTGTCTGCCTATTCACCGATTTTGATTCTCAGACAAATGTGAGCCAGAGCAAGGATTCTGATGTGTATATCACAGACAAAACCGTGCTAGACATGAGGTCTATGGACTTCAAGAGCAACAGCGCTGTGGCCTGGAGCAACAAATCTGACTTTGCATGTGCAAACGCCTTCAACAACAGCATTATTCCAGAAGACACCTTCTTCCCCAGCCCAGAAAGCTCCTGTGATGTCAAGCTGGTCGAGAAAAGCTTTGAAACAGATACCAACCTAAACTTTCAGAACCTGAGCGTGATTGGGTTCAGAATCCTCCTCCTGAAAGTGGCCGGGTTTAATCTGCTCATGACCCTGCGGCTGTGGTCCAGCTGA"

    if ABType == "A":

        #temp = "%s%s%s" % (F1R2Pri,seqFXHB2(CDR3Dna),VGeneShort)
        temp = "%s%s" % (F1R2Pri,seqFXHB2(CDR3Dna))
        TCRSeq = "%s%s%s" % (VGeneLong,seqFXHB2(temp),GDA)

    elif ABType == "B":
        #temp = "%s%s%s" % (VGeneShort,CDR3Dna,F1R2Pri)
        temp = "%s%s" % (CDR3Dna,F1R2Pri)
        TCRSeq = "%s%s%s" % (VGeneLong,temp,GDB)

    else:
        return False

    return TCRSeq


def TCRChainDesign(TCRNameList,TCRDict,workdir,sampleName):

    #design successful result
    head = "TCRName\tChain\tVGene\tDGene\tJGene\tCDR3Acid2\tCDR3Dna1\t2R1F\tPriCDR3Seq\tPriCDR3SeqAdj\tOLSeq\tVGeneShort\t1R2F\tVGeneLong\tTCRSeq\terrorInfo"
    TCRlinesList = [head]
    TCRCPriDict = {}  # TCR:{A:[xxx,yyy],B:[zzz]}  #TCR every chain's pri info
    TCRInfoDict = {}  # TCR:{A:[x,y],B:[z]}   #TCR every chain info.V:D:J:CDR3

    for t in TCRNameList: #every TCR
        for i in TCRDict[t]: #every chain in this TCR
            Pri1R = "-"  #A chain
            Pri2R = "-"  #A chain
            Pri1F = "-"  #B chain
            Pri2F = "-"  #B chain

            BefCDR3NoMat = "-"
            TCRSeq = "-"
            VGeneShortSeq = "-"
            OLSeq = "-"

            #get chain info
            ChainType = i[1]
            VGene = i[2]
            DGene = i[3]
            JGene = i[4]
            CDR3Acid = i[5]
            CDR3Dna = i[6]
            ChainInfo = "%s:%s:%s:%s" % (VGene,DGene,JGene,CDR3Acid)

            pre = "%s\t%s\t%s\t%s\t%s\t%s\t%s" % (t,ChainType,VGene,DGene,JGene,CDR3Acid,CDR3Dna)
            VGene = DealVGene(VGene)
        
            #deal JGene    
            JGene2 = getJGene(ChainType,JGene)
            if JGene2 == False:
                errorstage = "can't get JGene!"
                OutStri = "%s\t-\t-\t-\t-\t-\t-\t-\t%s" % (pre,errorstage)
                TCRlinesList.append(OutStri)
                continue

            #JGene find JPriAADict
            if JGene2 not in JPriAADict:
                errorstage = "J Gene not in JPriAADict!"
                OutStri = "%s\t-\t-\t-\t-\t-\t-\t-\t%s" % (pre,errorstage)
                TCRlinesList.append(OutStri)
                continue
            else:
                JGenePriAASeq = JPriAADict[JGene2]

            #deal CDR3 Seq  - Pri2R1F,FCDR3Dna
            CDR3SeqDealResult = CDR3SeqDeal(ChainType,CDR3Acid,CDR3Dna,JGenePriAASeq)
            if CDR3SeqDealResult == False:
                errorstage = "get Final CDR3Dna or Pri2R1F error!"
                OutStri = "%s\t-\t-\t-\t-\t-\t-\t-\t-\t%s" % (pre,errorstage)
                TCRlinesList.append(OutStri)
                continue
            else:
                Pri2R1F = CDR3SeqDealResult[0]
                FCDR3Dna = CDR3SeqDealResult[1]   #CDR3 seq(before,no match part)
                FCDR3DnaAdj = PriSeqSub(FCDR3Dna)

            #get OLSeq - OLSeq
            if Pri2R1F in PriOLSeqDict:
                OLSeq = PriOLSeqDict[Pri2R1F]
            else:
                errorstage = "get OLSeq error!"
                OutStri = "%s\t%s\t%s\t%s\t-\t-\t-\t-\t-\t%s" % (pre,Pri2R1F,FCDR3Dna,FCDR3DnaAdj,errorstage)
                TCRlinesList.append(OutStri)
                continue


            #get VGene Short Seq - VGeneShortSeq
            if VGene in VGeneSeqDict:
                VGeneShortSeq = VGeneSeqDict[VGene]
            else:
                errorstage = "VGene not in VGeneSeqDict!"
                OutStri = "%s\t%s\t%s\t%s\t%s\t-\t-\t-\t-\t%s" % (pre,Pri2R1F,FCDR3Dna,FCDR3DnaAdj,OLSeq,errorstage)
                TCRlinesList.append(OutStri)
                continue

            #get Pri1R(chainA) or Pri2F(chainB) - Pri1R2F
            #Pri1R2F = get1R2FPri(ChainType,FCDR3Dna,OLSeq,VGeneShortSeq)
            Pri1R2F = get1R2FPri(ChainType,FCDR3DnaAdj,OLSeq,VGeneShortSeq)
            if Pri1R2F == False:            
                errorstage = "get Pri1R2F error!"
                OutStri = "%s\t%s\t%s\t%s\t%s\t%s\t-\t-\t-\t%s" % (pre,Pri2R1F,FCDR3Dna,FCDR3DnaAdj,OLSeq,VGeneShortSeq,errorstage)
                TCRlinesList.append(OutStri)
                continue

            #get VGene Long Seq - VGeneLongSeq
            if VGene in VGeneLongSeqDict:
                VGeneLongSeq = VGeneLongSeqDict[VGene]
            else:
                errorstage = "VGene not in VGeneLongSeqDict!"
                OutStri = "%s\t%s\t%s\t%s\t%s\t%s\t%s\t-\t-\t%s" % (pre,Pri2R1F,FCDR3Dna,FCDR3DnaAdj,OLSeq,VGeneShortSeq,Pri1R2F,errorstage)
                TCRlinesList.append(OutStri)
                continue

            #get TCR seq - TCRSeq
            Pri2R1FSeq = R2F1PriDNASeqDict[Pri2R1F]
            TCRSeq = getTCRSeq(ChainType,Pri2R1FSeq,FCDR3DnaAdj,VGeneLongSeq)
            if TCRSeq:
                TCRSeq = TCRSeq
            else:
                errorstage = "get TCRseq error!"
                OutStri = "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t-\t%s" % (pre,Pri2R1F,FCDR3Dna,FCDR3DnaAdj,OLSeq,VGeneShortSeq,Pri1R2F,VGeneLongSeq,errorstage)
                TCRlinesList.append(OutStri)
                continue

            #successful design TCR
            OutStri = "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t-" % (pre,Pri2R1F,FCDR3Dna,FCDR3DnaAdj,OLSeq,VGeneShortSeq,Pri1R2F,VGeneLongSeq,TCRSeq)
            
            TCRlinesList.append(OutStri)

            if t not in TCRCPriDict:
                TCRCPriDict[t] = {"A":[],"B":[]}
                TCRInfoDict[t] = {"A":[],"B":[]}

            stri = "%s\t%s\t%s\t%s\t%s" % (Pri2R1F,Pri1R2F,FCDR3Dna,FCDR3DnaAdj,TCRSeq)
            TCRCPriDict[t][ChainType].append(stri)
            TCRInfoDict[t][ChainType].append(ChainInfo)

    #every TCR end.
    Head = "TCR\tChainInfo\t1F\t2F\t1R\t2R\tACDR3PriSeqRaw\tACDR3PriSeqAdj\tBCDR3ShortSeqRaw\tBCDR3ShortSeqAdj\tTCRSeq\n"
    OutLinesList = [Head]

    for t in TCRNameList:
  
        tflag = False
        if (t in TCRCPriDict) and (t in TCRInfoDict):
            tflag = True

        if tflag and len(TCRCPriDict[t]["A"]) > 0 and len(TCRCPriDict[t]["B"]) > 0 and len(TCRCPriDict[t]["A"]) == len(TCRInfoDict[t]["A"]) and len(TCRCPriDict[t]["B"]) == len(TCRInfoDict[t]["B"]):

            for a in range(0,len(TCRCPriDict[t]["A"])):
                for b in range(0,len(TCRCPriDict[t]["B"])):
                    tempA = TCRCPriDict[t]["A"][a].split("\t")
                    tempB = TCRCPriDict[t]["B"][b].split("\t")

                    TCRinfo = "%s;%s" % (TCRInfoDict[t]["A"][a],TCRInfoDict[t]["B"][b])
                    F1 = "%s" % (tempB[0])
                    F2 = "%s" % (tempB[1])

                    R1 = "%s" % (tempA[1])
                    R2 = "%s" % (tempA[0])

                    ACDR3 = "%s" % (tempA[2])
                    BCDR3 = "%s" % (tempB[2])
                    ACDR3Adj = "%s" % (tempA[3])
                    BCDR3Adj = "%s" % (tempB[3])

                    TCRSeq = "%s%s" % (tempB[4],tempA[4])  #!!!B-A

                    stri = "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % (t,TCRinfo,F1,F2,R1,R2,ACDR3,ACDR3Adj,BCDR3,BCDR3Adj,TCRSeq)
                    OutLinesList.append(stri)

                    
    #out
    OutFile1 = "%s/%s.TCRPriDesign.Detail.xls" % (workdir,sampleName)
    w = file(OutFile1,"w+")
    for i in TCRlinesList:
        i += "\n"
        w.write(i)
    w.close()

    OutFile2 = "%s/%s.TCRPriDesign.Final.xls" % (workdir,sampleName)
    w = file(OutFile2,"w+")
    for i in OutLinesList:
        w.write(i)
    w.close()

#main
#get order TCR Name
TCRNameSortList=[]
TCRDict = getTCRinput(TCRChainsTable)
for t in TCRDict:
    TCRNameSortList.append(t)
TCRNameSortList = TCRNameSort(TCRNameSortList)

#get DB
dataresult = getDatabase(databaseDir)
if dataresult:
    # AJPri.2.txt
    JPriAADict = dataresult[0]        #AJ10:[2R-10-1,GGGNKLTFGTGTQLKVELNIQNPD;x,x;x,x]
    # VGeneSeq.txt
    VGeneSeqDict = dataresult[1]      #TRAV1-1 GCAGAAGTAAGAGGCAGAGTCTT
    # 2R1FPriOLSeq.txt
    PriOLSeqDict = dataresult[2]      #1F-11-1 GAGGCCTTCTTCGGCCA
    # VGeneLongSeq.txt
    VGeneLongSeqDict = dataresult[3]  #TRAV1-1 ATGTGGGGAGCTTTCCTGCTCTATGTGTC
    # 2R1FPriDNASeq.txt
    R2F1PriDNASeqDict = dataresult[4] #2R-10-1 GTCAGGGTTCTGGATGTTCAGCTCCACCTTCAGCTGG

#design
TCRChainDesign(TCRNameSortList,TCRDict,workdir,sampleName)
